import React from "react";
import { useState } from "react";
import axios from "axios";
import { useEffect } from "react";


export default function Search() {
    const hotList=['热门','动画','视频','记录']
    const [searchInput, setInput] = useState('')
    const [searchHistory, setHistory] = useState([])
    const [searchList, setList] = useState([])
    
    useEffect(()=>{
        const historys=localStorage.getItem('searchHistory')
        if(historys){
            setHistory(JSON.parse(historys))
        }
        const getList=async()=>{
         const res=await axios.get('http://localhost:3000/list')
         console.log(res.data);
         if (Array.isArray(res.data)) {
            setList(res.data);
        }}
        getList()
     },[])
    const handleInput=(e)=>{
        setInput(e.target.value)
    }

    const handleSearch=()=>{
        if(searchInput && !searchHistory.includes(searchInput)){
            localStorage.setItem('searchHistory', JSON.stringify(searchHistory || []))
            setHistory([searchInput,...searchHistory])
            limitHistoryLength()
            setInput('')
        }
        const newList=searchList.filter(item=>item.title.includes(searchInput))
        setList(newList)
        
    }
    
    const limitHistoryLength = () => {
        if (searchHistory.length > 5) {
            setHistory(searchHistory.slice(0,5))
        }
    };
    const handleHistory = (clickedItem) => {
        const updatedHistory = searchHistory.filter(item => item!== clickedItem);
        setHistory([clickedItem,...updatedHistory]);
        setInput(clickedItem);
        handleSearch();
    };
    const clearList=()=>{
        setHistory([])
        localStorage.removeItem('searchHistory')
    }
    useEffect(()=>{
        localStorage.setItem('searchHistory',JSON.stringify(searchHistory))
    },[searchHistory])

    const handledelete=(index)=>{
        const arr = [...searchHistory]
        arr.splice(index,1)
        setHistory(arr)
    }
    return (
        <div>
            <input type="text" value={searchInput} placeholder="请输入搜索内容" onChange={handleInput} />
            <button onClick={handleSearch}>搜索</button>
            <h2>大家都在搜</h2>
            {hotList.map((item, index) => (
                <button key={index} onClick={() => setInput(item)}>{item}</button>
            ))}
            <h1>历史搜索</h1>
            {searchHistory.map((item, index) => (
                <>
                <span style={{marginLeft:'20px'}} key={index} onClick={()=>handleHistory(item)}>{item}</span><span onClick={handledelete}>X</span></>
                
            ))}
            <h1>搜索结果</h1>
            {
                searchList.map((item, index) => (
                    <div key={index}>
                        <p>{item.title}</p>
                    </div>
                ))
            }
            <h2><button onClick={()=>clearList()}>清空数据</button></h2>
        </div>
    )
}